package com.distributer.delayqueue.delayqueue.ready;

import java.util.Timer;
import java.util.concurrent.atomic.AtomicBoolean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.distributer.delayqueue.delayqueue.JobOperationService;
import com.distributer.delayqueue.delayqueue.Queue;
import com.distributer.delayqueue.delayqueue.consume.ConsoleComsumer;
import com.distributer.delayqueue.delayqueue.support.DistributedLock;
import com.distributer.delayqueue.delayqueue.support.RedisQueueProperties;
import com.distributer.delayqueue.support.LifeCycle;

public class ReadyQueueManager implements LifeCycle{

	private static final Logger LOGGER = LoggerFactory.getLogger(ReadyQueueManager.class);
	
	private static final String thread_name = "delay-ready-thread-%s";
	private boolean isDaemon = true;
	private AtomicBoolean isRunning = new AtomicBoolean(false);
	private RedisQueueProperties redisQueueProperties;
	private Timer timer;
	private JobOperationService jobOperationService;
	private DistributedLock lock;
	private Queue delayQueue;
	private String threadName;
	
	
	@Override
	public void start() {
		if (isRunning.compareAndSet(false, true)) {
			ReadyTimeTask readyTimeTask = new ReadyTimeTask();
			readyTimeTask.setConsumeQueueProvider(new ConsoleComsumer());
			readyTimeTask.setDelayQueue(delayQueue);
			readyTimeTask.setLock(lock);
			readyTimeTask.setRedisQueueProperties(redisQueueProperties);
			readyTimeTask.setJobOperationService(jobOperationService);
			threadName = String.format(thread_name, 1);
			timer = new Timer(threadName, isDaemon);
			timer.schedule(readyTimeTask, 500, redisQueueProperties.getReadyRoundRobindTime());
			LOGGER.info(String.format("started ready timer thredName - %s", threadName));
		}
	}

	@Override
	public void stop() {
		if (isRunning.compareAndSet(true, false)) {
			if (timer != null) {
				timer.cancel();
				LOGGER.info("stop ready timer threadName - %s",threadName);
			}
		}
	}

	@Override
	public boolean isRunning() {
		return isRunning.get();
	}

	public void setRedisQueueProperties(RedisQueueProperties redisQueueProperties) {
		this.redisQueueProperties = redisQueueProperties;
	}

	public void setJobOperationService(JobOperationService jobOperationService) {
		this.jobOperationService = jobOperationService;
	}

	public void setLock(DistributedLock lock) {
		this.lock = lock;
	}

	public void setDelayQueue(Queue delayQueue) {
		this.delayQueue = delayQueue;
	}
}
